// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const globalSettingsCollection = db.collection('globalSettings')

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 查询globalSettings集合中的数据
    // 如果没有指定key，则返回所有配置
    if (event.key) {
      const result = await globalSettingsCollection.where({
        key: event.key
      }).get()
      
      return {
        success: true,
        data: result.data.length > 0 ? result.data[0] : null
      }
    } else {
      const result = await globalSettingsCollection.get()
      return {
        success: true,
        data: result.data
      }
    }
  } catch (err) {
    return {
      success: false,
      error: err
    }
  }
}